import handler.PacketDecoder;
import handler.PacketEncoder;
import handler.Spliter;
import handler.server.LoginRequestHandler;
import handler.server.MessageRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

public class NettyServer {

    private static final int BEGIN_PORT = 8000;

    public static void main(String[] args) {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        final AttributeKey<Object> clientKey = AttributeKey.newInstance("clientKey");
        final AttributeKey<Object> serverName = AttributeKey.newInstance("serverName");
        serverBootstrap
            .group(boosGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .attr(serverName, "nettyServer")
            .childAttr(clientKey, "clientValue")
            // 请求队列大小
            .option(ChannelOption.SO_BACKLOG, 1024)
            // 开启 TCP 底层心跳机制
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            // 开启 nagle 算法
            .childOption(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<NioServerSocketChannel>() {
                @Override
                protected void initChannel(NioServerSocketChannel ch) throws Exception {
                    System.out.println("server 属性:" + ch.attr(serverName).get());
                }
            })
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) {
                    System.out.println("client 属性:" + ch.attr(clientKey).get());
                    ch.pipeline().addLast(new Spliter());
                    ch.pipeline().addLast(new PacketDecoder());
                    ch.pipeline().addLast(new LoginRequestHandler());
                    ch.pipeline().addLast(new MessageRequestHandler());
                    ch.pipeline().addLast(new PacketEncoder());
                }
            });

        bind(serverBootstrap, BEGIN_PORT);
    }

    private static void bind(final ServerBootstrap serverBootstrap, final int port) {
        // 异步方法，可以通过 Future 获取绑定端口消息
        serverBootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("端口[" + port + "]绑定成功!");
            } else {
                System.err.println("端口[" + port + "]绑定失败!");
                // bind(serverBootstrap, port + 1);
            }
        });
    }
}
